package com.example.view;

import com.example.client.AliImageAnalyzer;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.RenderingHints;

/**
 * 垃圾管理视图
 */
public class RubbishManagementView extends JPanel {
    // 垃圾管理相关组件
    private JButton fileChooserButton;
    private JLabel selectedFileLabel;
    private JTextArea resultTextArea;
    private File selectedImageFile;
    private JLabel imagePreviewLabel;
    
    public RubbishManagementView() {
        initializeUI();
    }
    
    private void initializeUI() {
        setLayout(new BorderLayout());
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        // 创建上部面板，包含文件选择和图片预览
        JPanel topPanel = new JPanel(new BorderLayout());
        
        // 文件选择区域
        JPanel fileSelectionPanel = createFileSelectionPanel();
        
        // 图片预览区域
        JPanel imagePreviewPanel = createImagePreviewPanel();
        
        // 将文件选择和预览区域添加到上部面板
        topPanel.add(fileSelectionPanel, BorderLayout.CENTER);
        topPanel.add(imagePreviewPanel, BorderLayout.EAST);
        
        // 结果显示区域
        JPanel resultPanel = createResultPanel();
        
        // 分析按钮
        JPanel analyzeButtonPanel = createAnalyzeButtonPanel();
        
        // 布局
        add(topPanel, BorderLayout.NORTH);
        add(resultPanel, BorderLayout.CENTER);
        add(analyzeButtonPanel, BorderLayout.SOUTH);
    }
    
    private JPanel createFileSelectionPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        panel.setBorder(BorderFactory.createTitledBorder("图片文件选择"));
        
        fileChooserButton = new JButton("选择图片文件");
        selectedFileLabel = new JLabel("未选择文件");
        selectedFileLabel.setForeground(Color.GRAY);
        
        fileChooserButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                chooseImageFile();
            }
        });
        
        panel.add(fileChooserButton);
        panel.add(Box.createHorizontalStrut(10));
        panel.add(selectedFileLabel);
        
        return panel;
    }
    
    private JPanel createImagePreviewPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder("图片预览"));
        panel.setPreferredSize(new Dimension(250, 280));
        
        imagePreviewLabel = new JLabel();
        imagePreviewLabel.setHorizontalAlignment(JLabel.CENTER);
        imagePreviewLabel.setVerticalAlignment(JLabel.CENTER);
        imagePreviewLabel.setPreferredSize(new Dimension(200, 200));
        imagePreviewLabel.setBorder(BorderFactory.createLoweredBevelBorder());
        imagePreviewLabel.setBackground(Color.WHITE);
        imagePreviewLabel.setOpaque(true);
        imagePreviewLabel.setText("<html><center>未选择图片<br/>点击左侧按钮选择</center></html>");
        imagePreviewLabel.setForeground(Color.GRAY);
        
        panel.add(imagePreviewLabel, BorderLayout.CENTER);
        
        return panel;
    }
    
    private JPanel createResultPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder("识别结果"));
        
        resultTextArea = new JTextArea(12, 50);
        resultTextArea.setEditable(false);
        resultTextArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
        resultTextArea.setBackground(new Color(248, 248, 248));
        resultTextArea.setText("请选择图片文件进行垃圾分类识别...");
        
        JScrollPane resultScrollPane = new JScrollPane(resultTextArea);
        panel.add(resultScrollPane, BorderLayout.CENTER);
        
        return panel;
    }
    
    private JPanel createAnalyzeButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        JButton analyzeButton = new JButton("开始分析");
        analyzeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                analyzeRubbish();
            }
        });
        panel.add(analyzeButton);
        
        return panel;
    }
    
    /**
     * 选择图片文件
     */
    private void chooseImageFile() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        
        // 设置文件过滤器，只允许选择图片文件
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "图片文件 (*.jpg, *.jpeg, *.png, *.gif, *.bmp)", 
            "jpg", "jpeg", "png", "gif", "bmp");
        fileChooser.setFileFilter(filter);
        
        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            selectedImageFile = fileChooser.getSelectedFile();
            selectedFileLabel.setText(selectedImageFile.getName());
            selectedFileLabel.setForeground(Color.BLACK);
            
            // 显示图片预览
            showImagePreview(selectedImageFile);
            
            // 清空之前的结果
            resultTextArea.setText("已选择图片文件: " + selectedImageFile.getName() + "\n点击\"开始分析\"按钮进行垃圾分类识别...");
        }
    }
    
    /**
     * 显示图片预览
     */
    private void showImagePreview(File imageFile) {
        try {
            // 读取图片
            BufferedImage originalImage = ImageIO.read(imageFile);
            if (originalImage == null) {
                imagePreviewLabel.setText("<html><center>无法显示预览<br/>文件格式不支持</center></html>");
                imagePreviewLabel.setIcon(null);
                return;
            }
            
            // 计算缩放尺寸，保持宽高比
            int originalWidth = originalImage.getWidth();
            int originalHeight = originalImage.getHeight();
            int maxSize = 180; // 预览图片最大尺寸
            
            double scale = Math.min((double) maxSize / originalWidth, (double) maxSize / originalHeight);
            int scaledWidth = (int) (originalWidth * scale);
            int scaledHeight = (int) (originalHeight * scale);
            
            // 创建缩放后的图片
            BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = scaledImage.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
            g2d.dispose();
            
            // 显示预览图片
            ImageIcon imageIcon = new ImageIcon(scaledImage);
            imagePreviewLabel.setIcon(imageIcon);
            imagePreviewLabel.setText("");
            
        } catch (IOException e) {
            imagePreviewLabel.setText("<html><center>预览加载失败<br/>" + e.getMessage() + "</center></html>");
            imagePreviewLabel.setIcon(null);
        }
    }
    
    /**
     * 分析垃圾分类
     */
    private void analyzeRubbish() {
        if (selectedImageFile == null) {
            JOptionPane.showMessageDialog(this, 
                "请先选择一个图片文件", 
                "提示", 
                JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        resultTextArea.setText("正在分析图片，请稍候...\n");
        
        // 在后台线程中调用API，避免阻塞UI
        SwingWorker<String, String> worker = new SwingWorker<String, String>() {
            @Override
            protected String doInBackground() throws Exception {
                // 调用阿里云图像识别API
                return AliImageAnalyzer.analyzeRubbishImage(selectedImageFile.getAbsolutePath());
            }
            
            @Override
            protected void process(List<String> chunks) {
                // 可以在这里处理中间状态更新
                for (String message : chunks) {
                    resultTextArea.append(message);
                }
            }
            
            @Override
            protected void done() {
                try {
                    String result = get();
                    resultTextArea.setText(String.format(
                        "文件: %s\n" +
                        "文件大小: %.2f KB\n" +
                        "分析时间: %s\n\n" +
                        "%s",
                        selectedImageFile.getName(),
                        selectedImageFile.length() / 1024.0,
                        new java.util.Date().toString(),
                        result
                    ));
                } catch (Exception e) {
                    resultTextArea.setText(String.format(
                        "分析失败:\n" +
                        "错误信息: %s\n" +
                        "错误类型: %s\n\n" +
                        "请检查:\n" +
                        "1. 网络连接是否正常\n" +
                        "2. 阿里云访问凭据是否正确设置\n" +
                        "3. 图片文件是否有效",
                        e.getMessage(),
                        e.getClass().getSimpleName()
                    ));
                }
            }
        };
        
        worker.execute();
    }
} 